import axios from 'axios';
import store from '../store';
import { message as Message } from 'ant-design-vue'

// 配置axios请求的baseURL
// axios.defaults.baseURL = '';
// axios.defaults.headers['Content-Type'];

// 配置响应拦截器
// axios.interceptors.response.use(
//   response => {
//     // 分析响应数据，处理响应拦截
//     return Promise.resolve(response);
//   },
//   error => {
//     // 处理错误
//     return Promise.reject(error);
//   }
// );

// 封装一般请求方法
const doRequest = (url = '', options = {}) => {
  return new Promise((resolve, reject) => {
    const serverUrl = store.state.serverUrl
    options.method = options.method || 'GET';
    options.data = options.data || {};
    options.params = options.params || {};
    options.headers = options.headers || { 'TM-TOKEN': store.state.token };

    let req = {
      url: `${serverUrl}/api${url}`,
      method: options.method,
      data: options.data,
      params: options.params,
      headers: options.headers
    }

    if (options.blob) {
      req = { ...req, responseType: 'blob' }
    }

    axios.request(req)
      .then(response => {
        resolve(response);
      })
      .catch(error => {
        Message.warn(`网络请求失败:${error.messge}`)
        reject(error);
      });
  });
};

// 封装包含认证的一般请求方法
const doAuthRequest = (url = '', options = {}) => {
  return new Promise((resolve, reject) => {
    const token = localStorage.getItem('access_token') || '';
    options.params.token = token;
    doRequest(url, options)
      .then(response => {
        resolve(response);
      })
      .catch(error => {
        reject(error);
      });
  });
};

const request = {
  doRequest,
  doAuthRequest
};

export default request;
